﻿namespace MicroCloud.Entity.BatchConfiguration
{
    /// <summary>
    /// 配置实体属性主键规则
    /// </summary>
    public class PropertyKeyConfiguration : IEntityBatchConfiguration
    {
        /// <summary>
        /// 配置指定的<see cref="IMutableEntityType"/>
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        /// <param name="mutableEntityType">实体的 <see cref="IMutableEntityType"/> 类型</param>
        /// <param name="database">数据库相关信息和操作的访问 <see cref="DatabaseFacade"/> 类型</param>
        /// <param name="dbContextOptions">数据上下文配置 <see cref="DbContextOption"/> 类型</param>
        /// <param name="dbContextType">数据上下文类型</param>
        public void Configure(ModelBuilder modelBuilder, IMutableEntityType mutableEntityType, DatabaseFacade database, DbContextOption dbContextOptions, Type dbContextType)
        {
            var clrType = mutableEntityType.ClrType;
            //var keyProp = clrType.GetProperties().FirstOrDefault(o => o.MemberType == MemberTypes.Property && !o.IsVirtual() && o.GetAttribute<NotMappedAttribute>() == null && (o.GetAttribute<KeyAttribute>() != null || o.Name.ToUpper().Equals("ID")));
            var keyProp = clrType.GetProperties().FirstOrDefault(o => o.MemberType == MemberTypes.Property && o.GetAttribute<NotMappedAttribute>() == null && (o.GetAttribute<KeyAttribute>() != null || o.Name.ToUpper().Equals("ID")));
            if (keyProp != null)
            {
                var keyPropertyBuilder = modelBuilder.Entity(clrType).Property(keyProp.Name);
                //根据规则设置主键是否自增（int、long类型主键）
                if (typeof(int).Equals(keyProp.PropertyType) || typeof(long).Equals(keyProp.PropertyType))
                {
                    var valueGenerateAttribute = clrType.GetAttribute<ValueGenerateAttribute>();
                    //Console.WriteLine($"根据规则设置主键是否自增，规则：{valueGenerateAttribute.GenerateRule}");
                    if (valueGenerateAttribute != null)
                    {
                        switch (valueGenerateAttribute.GenerateRule)
                        {
                            case ValueGenerateRule.Never:
                                //将属性配置为在保存此实体类型的实例时从不具有数据库生成的值。
                                keyPropertyBuilder.ValueGeneratedNever();
                                break;
                            case ValueGenerateRule.OnAdd:
                                //将属性配置为仅在保存新实体时生成值，除非设置了非空的非临时值，在这种情况下，将改为保存设置的值。
                                //该值可以由客户端值生成器生成，也可以由数据库生成，作为保存实体的一部分。
                                keyPropertyBuilder.ValueGeneratedOnAdd();
                                break;
                            case ValueGenerateRule.OnAddOrUpdate:
                                //将属性配置为在保存新实体或现有实体时生成值。
                                keyPropertyBuilder.ValueGeneratedOnAddOrUpdate();
                                break;
                            case ValueGenerateRule.OnUpdate:
                                //将属性配置为在保存现有实体时生成值。
                                keyPropertyBuilder.ValueGeneratedOnUpdate();
                                break;
                            case ValueGenerateRule.OnUpdateSometimes:
                                //将属性配置为在保存现有实体时在特定条件下生成的值。
                                keyPropertyBuilder.ValueGeneratedOnUpdateSometimes();
                                break;
                        }
                    }
                }
                //string 类型主键限定长度 128
                else if (typeof(string).Equals(keyProp.PropertyType))
                {
                    var stringLengthAttribute = clrType.GetAttribute<StringLengthAttribute>();
                    var maxLengthAttribute = clrType.GetAttribute<MaxLengthAttribute>();
                    var maxLength1 = stringLengthAttribute == null ? 0 : stringLengthAttribute.MaximumLength;
                    var maxLength2 = maxLengthAttribute == null ? 0 : maxLengthAttribute.Length;
                    var maxLength = maxLength1 > maxLength2 ? maxLength1 : maxLength2;
                    if (maxLength <= 0)
                    {
                        //默认长度：常规类型 - 128
                        keyPropertyBuilder.HasMaxLength(DataTableConstants.StringKeyDefaultLength);
                    }
                    //keyPropertyBuilder.HasColumnType($"nvarchar({_stringKeyDefaultLength})");
                    keyPropertyBuilder.IsUnicode();
                }
            }
        }

    }

}
